import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

//客户端
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient() throws IOException {

        //new 这个对象需要和服务器建立连接
        //要建立连接就要知道服务器在哪里( 类比打电话 ,需要知道号码是什么)
        socket = new Socket("127.0.0.1",8000);
    }

    public void start() throws IOException {
        //因为是长连接,要写循环
        Scanner scanner = new Scanner(System.in);
        //对输入输出进行包装
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner( inputStream);
            PrintWriter printwriter = new PrintWriter(outputStream);

            while( true) {
                //1.从控制台读取用户的输入
                System.out.printf(">");
                String requst = scanner.next();
                //2. 把请求发送给服务器
                printwriter.println(requst);
                printwriter.flush();
                //3. 从服务器读取响应
                String response = scannerNet.next();
                //4. 把结果显示到界面上
                System.out.printf("req : %s, resp: %s\n",requst ,response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient();
        client.start();
    }
}